package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;

    @Autowired
    private BpmnInfoServiceImpl bpmnInfoService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private CarPackageAuditServiceImpl carPackageAuditService;

    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());


        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        // 设置createTime
        serviceItem.setCreateTime(new Date());
        // 根据前台传过来的是否套餐
        if (ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())) {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        } else {
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        // 处于上架的商品不能修改
        ServiceItem service = this.get(serviceItem.getId());

        if (service.getSaleStatus().equals(ServiceItem.SALESTATUS_ON) ||
                service.getAuditStatus().equals(ServiceItem.AUDITSTATUS_AUDITING)) {
            throw new BusinessException("非法状态异常，上架的商品或是处于审核中不能修改");
        }

        // 如果是套餐并且处于审核通过的状态，那么只要编辑修改了数据，我们就把审核状态修改成初始化状态
        if (ServiceItem.CARPACKAGE_YES.equals(service.getCarPackage()) &&
                ServiceItem.AUDITSTATUS_APPROVED.equals(service.getAuditStatus())) {
            // 审核状态修改成初始化状态
            service.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }

        // 套餐和创建时间 上架下架状态都不让修改
        service.setName(serviceItem.getName());
        service.setOriginalPrice(serviceItem.getOriginalPrice());
        service.setDiscountPrice(serviceItem.getDiscountPrice());
        service.setInfo(serviceItem.getInfo());
        service.setServiceCatalog(serviceItem.getServiceCatalog());
        service.setId(serviceItem.getId());


        serviceItemMapper.updateByPrimaryKey(service);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOff(Long id) {
        // 下架
        ServiceItem serviceItem = this.get(id);
        // 必须是上架状态才能下架 否则抛出异常
        if (!serviceItem.getSaleStatus().equals(ServiceItem.SALESTATUS_ON)) {
            throw new BusinessException("只有上架才能下架");
        }
        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void saleOn(Long id) {
        // 上架
        ServiceItem serviceItem = this.get(id);

        // 必须是处于下架才能上架 非套餐可以直接上架 是套餐，必须要审核通过的状态才可以上架
        if (serviceItem.getSaleStatus() != 0) {
            throw new BusinessException("非法状态异常 正上架状态");
        }
        // 是套餐但不是审核通过状态就抛异常
        if (serviceItem.getCarPackage().equals(ServiceItem.CARPACKAGE_YES)
                && !serviceItem.getAuditStatus().equals(ServiceItem.AUDITSTATUS_APPROVED)) {
            throw new BusinessException("非法状态异常 套餐必须要审核通过状态才能上架");
        }

        serviceItemMapper.changeSaleStatus(id, ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void startAudit(Long serviceItemId, Long bpmnInfoId, Long director, Long finance, String info) {
            // 根据传入的服务项id查询状态是不是初始化 不是抛异常
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(serviceItemId);
        // 判断满足审核条件 必须是套餐 状态必须是初始化
        if (serviceItem == null || serviceItem.getAuditStatus() != ServiceItem.AUDITSTATUS_INIT
             || serviceItem.getCarPackage() != ServiceItem.CARPACKAGE_YES ) {
            throw new BusinessException("参数异常,不是初始化状态");
        }
        // 到这修改审核状态 审核中
        serviceItemMapper.changeSaleStatus(serviceItemId,ServiceItem.AUDITSTATUS_AUDITING);

        //获取套餐审核对象
        CarPackageAudit audit = new CarPackageAudit();
        // 保存审核信息记录
        audit.setServiceItemId(serviceItemId);
        // 设置备注
        audit.setServiceItemInfo(serviceItem.getInfo());
        //设置折扣价
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreateTime(new Date());
        audit.setCreator(ShiroUtils.getUser().getUserName());
        audit.setBpmnInfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setAuditorId(director);
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);

        carPackageAuditService.save(audit);

        // 设置相关参数 启动流程实例
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        String processDefinitionKey = bpmnInfo.getActProcessKey();
        String businessKey = audit.getId().toString();
        HashMap<String, Object> map = new HashMap<>();
        // activiti 不支持bigDecimal
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        if(director != null){
            map.put("director",director.toString());
        }
        if(finance != null){
            map.put("finance",finance.toString());
        }
        //按键启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey, map);
        //修改实例 ID
        audit.setInstanceId(processInstance.getId());

        carPackageAuditService.update(audit);

    }

    @Override
    public void changAuditStatus(Long serviceItemId, Integer auditstatusInit) {
        serviceItemMapper.changeSaleStatus(serviceItemId,auditstatusInit);
    }
}



